package com.xjgz.aio.socket.pro.extension.plugins;

import com.xjgz.aio.socket.StateMachineEnum;
import com.xjgz.aio.socket.transport.AioQuickClient;
import com.xjgz.aio.socket.transport.AioSession;

import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;

public class ReconnectPlugin<T> extends AbstractPlugin<T> {

    private final AsynchronousChannelGroup asynchronousChannelGroup;

    private final AioQuickClient client;

    private boolean shutdown = false;

    public ReconnectPlugin(AioQuickClient client) {
        this(client, null);
    }

    public ReconnectPlugin(AioQuickClient client, AsynchronousChannelGroup asynchronousChannelGroup) {
        this.asynchronousChannelGroup = asynchronousChannelGroup;
        this.client = client;
    }

    @Override
    public void stateEvent(StateMachineEnum stateMachineEnum, AioSession session, Throwable throwable) {
        if (stateMachineEnum != StateMachineEnum.SESSION_CLOSED || shutdown) {
            return;
        }
        try {
            if (asynchronousChannelGroup == null) {
                client.start();
            } else {
                client.start(asynchronousChannelGroup);
            }
        } catch (IOException e) {
            shutdown = true;
            e.printStackTrace();
        }
    }

    public void shutdown() {
        shutdown = true;
    }
}
